package cn.sfrog.project.biz.web.controller;

import cn.sfrog.common.constant.ConfigConstants;
import cn.sfrog.common.core.controller.BaseController;
import cn.sfrog.common.core.domain.ApiAjaxResult;
import cn.sfrog.common.core.page.TableDataInfo;
import cn.sfrog.common.enums.StatusEnum;
import cn.sfrog.common.enums.UserTypeEnum;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.project.biz.admin.domain.vo.BizRechargeUnitQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizRechargeUnitVO;
import cn.sfrog.project.biz.admin.service.*;
import cn.sfrog.project.biz.web.service.AppUserService;
import cn.sfrog.project.biz.web.vo.account.*;
import cn.sfrog.project.biz.web.vo.index.AppSysConfigResultVO;
import cn.sfrog.system.domain.vo.app.AppUserResultVO;
import cn.sfrog.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/userAccount")
@Api(value = "/api/userAccount", tags = "APP用户账户相关")
public class AppUserAccountController extends BaseController {

    @Autowired
    private IBizWithdrawBankCardService bizWithdrawBankCardService;
    @Autowired
    private IBizUserWithdrawRecordService bizUserWithdrawRecordService;
    @Autowired
    private IBizUserAccountService bizUserAccountService;
    @Autowired
    private IBizRechargeUnitService bizRechargeUnitService;
    @Autowired
    private IBizUserGiveAwayRecordService bizUserGiveAwayRecordService;
    @Autowired
    private IBizUserTradeRecordService bizUserTradeRecordService;
    @Autowired
    private IBizUserRechargeService bizUserRechargeService;
    @Autowired
    private AppUserService appUserService;

    @Autowired
    private ISysConfigService sysConfigService;

    @ApiOperation(value = "我的账户")
    @GetMapping("/getMyAccount")
    public ApiAjaxResult<AppUserAccountResultVO> getMyAccount(){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        AppUserAccountResultVO accountResultVO = bizUserAccountService.selectAppMyAccount(userId);
        return ApiAjaxResult.success(accountResultVO);
    }


    @ApiOperation(value = "新增银行卡")
    @PostMapping("/saveBankCard")
    public ApiAjaxResult saveBankCard(@RequestBody @Validated AppUserBankCardFormVO form){
        return ApiAjaxResult.success(bizWithdrawBankCardService.saveBankCard(form));
    }

    @ApiOperation(value = "获取银行卡列表")
    @GetMapping("/getBankCardList")
    public ApiAjaxResult<List<AppUserBankCardResultVO>> getBankCardList(){
        List<AppUserBankCardResultVO> bankCardList = bizWithdrawBankCardService.selectAppUserBankCardList(SecurityUtils.getLoginUser().getUser().getUserId());
        return ApiAjaxResult.success(bankCardList);
    }

    @ApiOperation(value = "申请提现")
    @PostMapping("/applyWithdraw")
    public ApiAjaxResult applyWithdraw(@RequestBody @Validated AppUserApplyWithdrawFormVO form){
        return ApiAjaxResult.success(bizUserWithdrawRecordService.applyWithdraw(form));
    }

    @ApiOperation(value = "获取充值数量列表")
    @GetMapping("/getRechargeUnitList")
    public ApiAjaxResult<List<BizRechargeUnitVO>> getRechargeUnitList(){
        BizRechargeUnitQueryVO queryVO = new BizRechargeUnitQueryVO();
        queryVO.setStatus(StatusEnum.active.toString());
        List<BizRechargeUnitVO> rechargeUnitList = bizRechargeUnitService.selectBizRechargeUnitList(queryVO);
        return ApiAjaxResult.success(rechargeUnitList);
    }

    @ApiOperation(value = "转赠")
    @PostMapping("/giveAway")
    public ApiAjaxResult giveAway(@RequestBody @Validated AppUserGiveAwayFormVO form){
         return ApiAjaxResult.success(bizUserGiveAwayRecordService.saveUserGiveAwayRecord(form));
    }

    @ApiOperation(value = "获取手机号下所有的身份")
    @GetMapping("/getUserList/{phone}")
    public ApiAjaxResult getUserListByPhone(@PathVariable("phone") String phone){
        List<AppUserResultVO> userResultVOList = appUserService.selectAppUserList(phone);
        for (AppUserResultVO vo:userResultVOList) {
            if(UserTypeEnum.MEMBER.getCode().equals(vo.getUserType())){
                vo.setUserTypeName("会员");
            }else if(UserTypeEnum.ESCORT.getCode().equals(vo.getUserType())){
                vo.setUserTypeName("陪诊");
            }else if(UserTypeEnum.CARE_WORKER.getCode().equals(vo.getUserType())){
                vo.setUserTypeName("护工");
            }else if(UserTypeEnum.CARE_NURSE.getCode().equals(vo.getUserType())){
                vo.setUserTypeName("护士");
            }else if(UserTypeEnum.DOCTOR.getCode().equals(vo.getUserType())){
                vo.setUserTypeName("医生");
            }
        }
        return ApiAjaxResult.success(userResultVOList);
    }


    @ApiOperation(value = "获取交易明细列表")
    @GetMapping("/getTradeRecordList")
    public TableDataInfo<AppUserTradeRecordResultVO> getTradeRecordList(AppUserTradeRecordQueryVO queryVO){
        queryVO.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        startPage();
        List<AppUserTradeRecordResultVO> tradeRecordList = bizUserTradeRecordService.selectAppUserTradeRecordList(queryVO);

        List<AppUserTradeRecordResultVO> tradeRecordList2 = bizUserTradeRecordService.selectAppUserTradeRecordList(queryVO);

        //查询本月获取和消耗
        List<AppUserTradeRecordResultVO> gainList = tradeRecordList2.stream().filter(item -> item.getTradeAmount().compareTo(BigDecimal.ZERO) == 1).collect(Collectors.toList());
        List<AppUserTradeRecordResultVO> consumeList = tradeRecordList2.stream().filter(item -> item.getTradeAmount().compareTo(BigDecimal.ZERO) == -1).collect(Collectors.toList());
        BigDecimal gainAmount = gainList.stream().map(x -> x.getTradeAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal consumeAmount = consumeList.stream().map(x -> x.getTradeAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
        HashMap<String, Object> map = new HashMap<>();
        map.put("gainAmount",gainAmount.abs());
        map.put("consumeAmount",consumeAmount.abs());
        TableDataInfo dataTable = getDataTable(tradeRecordList);
        dataTable.setExts(map);
        return dataTable;
    }

    @ApiOperation(value = "充值")
    @PostMapping("/recharge")
    public ApiAjaxResult recharge(@RequestBody @Validated AppUserRechargeFormVO form){
        if("".equals(form.getOpenId().toString())){
            throw new RuntimeException("openId不能为空,可能网络错误，请稍后再试");
        }
        try {
            return ApiAjaxResult.success(bizUserRechargeService.recharge(form));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation(value = "获取陪护豆兑换比例")
    @GetMapping("/getExchangeScale")
    public ApiAjaxResult<AppSysConfigResultVO> getSysConfig(){
        AppSysConfigResultVO vo = new AppSysConfigResultVO();
        String s = sysConfigService.selectConfigByKey(ConfigConstants.ESCORT_BEAN_EXCHANGE_SCALE);
        vo.setScale(s + ":1");
        return ApiAjaxResult.success(vo);
    }

}
